#!/usr/bin/python3
# -*- coding:utf-8 -*-
# @Time   :2021/12/23
# @Author :CJX
# @File   :dox_enquiry.py
# 该库用于查询继电器板do，di状态

import can


def di_status(di_location):  # 输入要查询的di点
    bus = can.Bus(interface='socketcan', channel='can0', receive_own_messages=eval('False'))
    inquiry_di = can.Message(arbitration_id=0x0301, data=[0x01], is_extended_id=False)
    bus.send(inquiry_di)  # 0x0301  返回769/0x0301 di状态
    message_di = bus.recv(timeout=1)  # 接收数据
    type_id_di = message_di.arbitration_id  # 返回can报文类型

    if type_id_di == 769:
        # time_float2 = message_di.timestamp          # 浮点数时间戳
        # time_date2 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(float(message_di.timestamp)))  # 转str时间

        # data3 = message_di.data[0:4]  # 取回4个字,预留32通道,bytearray->int->bin(str)->去'0b'->bin->左补32位->反向排列
        data_di = '{:0>32b}'.format(int(bin(int.from_bytes(message_di.data[0:4], "little")).replace('0b', ''), 2))[::-1]

    di_location = list(data_di)[di_location - 1]  # 字符串转列表输出
    return di_location


def do_status(do_location):  # # 输入要查询的do点
    bus = can.Bus(interface='socketcan', channel='can0', receive_own_messages=eval('False'))
    inquiry_do = can.Message(arbitration_id=0x0201, data=[0x01], is_extended_id=False)  # 问询
    bus.send(inquiry_do)  # 0x0201 DO状态 返回513
    message_do = bus.recv(timeout=1)  # 接收数据
    type_id_do = message_do.arbitration_id  # 返回can报文类型

    if type_id_do == 513:
        # time_float1 = message_do.timestamp          # 浮点数时间戳
        # time_date1 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(float(message_do.timestamp)))  # 转str时间
        # 取回4个字节,预留32通道,bytearray->int->bin(str)->去'0b'->bin->左补32位
        data_do = '{:0>32b}'.format(int(bin(int.from_bytes(message_do.data[0:4], "little")).replace('0b', ''), 2))[::-1]

    do_location = list(data_do)[do_location - 1]  # 字符串转列表输出
    return do_location


def di_status_4_8_13(di_4_8_13_location):  # 输入要查询的di点
    bus = can.Bus(interface='socketcan', channel='can0', receive_own_messages=eval('False'))
    inquiry_di = can.Message(arbitration_id=0x0301, data=[0x01], is_extended_id=False)
    bus.send(inquiry_di)  # 0x0301  返回769/0x0301 di状态
    message_di = bus.recv(timeout=1)  # 接收数据
    type_id_di = message_di.arbitration_id  # 返回can报文类型

    if type_id_di == 769:
        # time_float2 = message_di.timestamp          # 浮点数时间戳
        # time_date2 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(float(message_di.timestamp)))  # 转str时间

        # data3 = message_di.data[0:4]  # 取回4个字,预留32通道,bytearray->int->bin(str)->去'0b'->bin->左补32位->反向排列
        data_di = '{:0>32b}'.format(int(bin(int.from_bytes(message_di.data[0:4], "little")).replace('0b', ''), 2))[::-1]

    di_location = list(data_di)  # 字符串转列表输出

    di_4_8_13_location = str(
        int(di_location[3]) + int(di_location[4]) + int(di_location[6]) + int(di_location[7]) + int(
            di_location[11]) + int(di_location[12]))

    return di_4_8_13_location
